import React, { useState, useEffect } from 'react';
import { processVehicleEntry, processVehicleExit, getParkingSpots } from '../services/api';

const DevTools = () => {
  const [plateNumber, setPlateNumber] = useState('');
  const [spotNumber, setSpotNumber] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const [parkingSpots, setParkingSpots] = useState([]);
  const [activeVehicles, setActiveVehicles] = useState([]);
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  // 加载所有车位信息
  useEffect(() => {
    const fetchParkingSpots = async (showLoading = false) => {
      try {
        if (showLoading) {
          // 仅在首次加载时设置loading状态
          setIsInitialLoad(false);
        }
        const response = await getParkingSpots();
        setParkingSpots(response.data);
      } catch (err) {
        console.error('加载车位信息失败', err);
      }
    };

    // 首次加载
    fetchParkingSpots(true);
    
    // 每5秒刷新一次车位信息，属于不太重要的操作性数据
    const intervalId = setInterval(() => fetchParkingSpots(false), 5000);
    return () => clearInterval(intervalId);
  }, []);

  // 车牌示例
  const plateExamples = ['京A12345', '沪B67890', '粤C13579', '津D24680'];

  // 处理随机车牌生成
  const generateRandomPlate = () => {
    const randomPlate = plateExamples[Math.floor(Math.random() * plateExamples.length)];
    setPlateNumber(randomPlate);
  };

  // 处理车辆入场
  const handleVehicleEntry = async () => {
    if (!plateNumber.trim()) {
      setError('请输入车牌号');
      return;
    }
    if (!spotNumber.trim()) {
      setError('请选择车位号');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const response = await processVehicleEntry({
        plate_number: plateNumber,
        spot_number: spotNumber
      });
      
      setResult({
        success: true,
        message: `车辆 ${plateNumber} 成功进入车位 ${spotNumber}`,
        details: response.data
      });
      
      // 添加到当前活跃车辆列表
      setActiveVehicles(prev => [...prev, {
        plateNumber,
        spotNumber,
        entryTime: new Date().toLocaleString()
      }]);
      
      // 重置表单
      setPlateNumber('');
      setSpotNumber('');
    } catch (err) {
      console.error('车辆入场处理失败', err);
      setError(err.response?.data?.detail || '车辆入场处理失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理车辆出场
  const handleVehicleExit = async (plate = null) => {
    const exitPlate = plate || plateNumber;
    
    if (!exitPlate.trim()) {
      setError('请输入车牌号');
      return;
    }

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const response = await processVehicleExit({
        plate_number: exitPlate
      });
      
      setResult({
        success: true,
        message: `车辆 ${exitPlate} 成功离开停车场`,
        details: response.data
      });
      
      // 从活跃车辆列表中移除
      setActiveVehicles(prev => prev.filter(v => v.plateNumber !== exitPlate));
      
      // 如果是通过点击按钮触发的，不重置车牌输入
      if (!plate) {
        setPlateNumber('');
      }
    } catch (err) {
      console.error('车辆出场处理失败', err);
      setError(err.response?.data?.detail || '车辆出场处理失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold text-yellow-600 mb-6">开发者工具 - 车辆出入模拟</h1>
      
      <div className="grid md:grid-cols-2 gap-8">
        {/* 左侧：表单 */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <h2 className="text-xl font-semibold mb-4">模拟车辆进出</h2>
          
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">
              车牌号
            </label>
            <div className="flex">
              <input
                type="text"
                value={plateNumber}
                onChange={(e) => setPlateNumber(e.target.value)}
                placeholder="输入车牌号，如：京A12345"
                className="shadow appearance-none border rounded py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline flex-grow"
              />
              <button
                onClick={generateRandomPlate}
                className="ml-2 bg-gray-200 hover:bg-gray-300 text-gray-800 py-2 px-4 rounded focus:outline-none focus:shadow-outline"
              >
                随机
              </button>
            </div>
          </div>
          
          <div className="mb-6">
            <label className="block text-gray-700 text-sm font-bold mb-2">
              车位号
            </label>
            <select
              value={spotNumber}
              onChange={(e) => setSpotNumber(e.target.value)}
              className="shadow border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
            >
              <option value="">选择车位</option>
              {parkingSpots.map((spot) => (
                <option 
                  key={spot.spot_number} 
                  value={spot.spot_number}
                  disabled={spot.status === 'occupied'}
                >
                  {spot.spot_number} ({spot.status === 'free' ? '空闲' : '已占用'})
                </option>
              ))}
            </select>
          </div>
          
          <div className="flex space-x-4">
            <button
              onClick={handleVehicleEntry}
              disabled={loading}
              className="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex-1"
            >
              {loading ? '处理中...' : '模拟入场'}
            </button>
            
            <button
              onClick={() => handleVehicleExit()}
              disabled={loading}
              className="bg-yellow-600 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline flex-1"
            >
              {loading ? '处理中...' : '模拟出场'}
            </button>
          </div>
          
          {error && (
            <div className="mt-4 p-3 bg-red-100 text-red-700 rounded-md">
              {error}
            </div>
          )}
          
          {result && (
            <div className="mt-4 p-3 bg-green-100 text-green-700 rounded-md">
              <p className="font-bold">{result.message}</p>
              {result.details && (
                <pre className="mt-2 text-xs overflow-auto">
                  {JSON.stringify(result.details, null, 2)}
                </pre>
              )}
            </div>
          )}
        </div>
        
        {/* 右侧：当前在场车辆列表 */}
        <div className="bg-white p-6 rounded-lg shadow-md">
          <h2 className="text-xl font-semibold mb-4">当前在场车辆</h2>
          
          {activeVehicles.length === 0 ? (
            <p className="text-gray-500 italic">当前没有在场车辆</p>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      车牌号
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      车位号
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      入场时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {activeVehicles.map((vehicle) => (
                    <tr key={vehicle.plateNumber}>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {vehicle.plateNumber}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {vehicle.spotNumber}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {vehicle.entryTime}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <button
                          onClick={() => handleVehicleExit(vehicle.plateNumber)}
                          className="text-yellow-600 hover:text-yellow-900"
                        >
                          出场
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default DevTools; 